<?php

//工具类
class Util{
	public function __construct(){}

	/**
	 *
	 * 批量设置cookie
	 * 参数：$arr，cookie名称和value的关联数组;其他参数详见手册.
	 * masonsu 2010-3-9
	*/
	public static function set_all_cookie($arr,$expire=0,$path='',$domain='',$secure='',$httponly='')
	{
		if(is_array($arr))
		{
			foreach($arr as $key => $value)
			{
				setcookie($key,$value,$expire,$path,$domain,$secure,$httponly);
			}
		}
	}

	/*
     * 翻页方法
     *
     * @param int $count                   总数
     * @param int $limit                   每页最多显示多少数据
	 * @param int $offset                  偏移量
     * @param int $page                    当前页码数
     * @param string $url                  处理程序名
     * @param mixed $urlext                url扩展参数
     * @param string $pname                页面参数名称
     * @param bool $flag                   是否显示首尾页
     *
     * return string             返回的分页按钮(样式显示须引入相关ＣＳＳ文件)
	 *                                       http://ihome.sohu.com/css/style.css
     *
	 * masonsu 2010-3-11
     */
    public static function showPage($count, $limit, $offset,$page, $url, $urlext="", $pname='page', $flag=false) 
	{
		//样式原型
        //$str_page = "<div class='left'>共 <em class='org'><{$count}></em> 条记录 这是 <em class='org'><{$start}>-<{$end}></em> 条</div><span class='page_num'><a href='member_management.php?page=<{$page_end}>'>&gt;&gt;</a></span><span class='page_num'><a href='#'>&gt;</a></span><span class='page_num'><a href='#'>2</a></span><span class='page_num_nonce'>1</span><span class='page_nolink'>&lt;</span><span class='page_num'><a href='member_management.php?page=<{$page_start}>'>&lt;&lt;</a></span>";
		
		$pNums = ceil($count / $limit);         //计算总页数

		$str_page = '';

        $iLength    = 4;
        $page = intval($page);
        $pname = trim($pname);
        if ($page <= 0) {
        	$page = 1;
        }
        if (!$pname) {
        	$pname = "page";
        }
        if (is_array($urlext)) {
        	$urlextend  = http_build_query($urlext);
        }elseif (is_string($urlext)){
        	$urlextend  = trim($urlext);
        }
        ! empty($urlextend) && $urlextend = $urlextend."&";

		$page_start = $count?($offset+1):0;
		$page_end = (($offset+$limit)>$count)?$count:($offset+$limit);

		$str_page .= "<div class='left'>共 <em class='org'>".$count."</em> 条记录 这是 <em class='org'>".$page_start."-".$page_end."</em> 条</div>";

        $start  = $page - $iLength;
        ($start < 1) && $start = 1;
        $end    = $start + 2 * $iLength;
        ($end > $pNums) && $end = $pNums;

        $leftLen    = $page - $start;
        $rightLen   = $end - $page;

        if($end - $start < 2 * $iLength) {    //补齐长度
            ($leftLen <= $iLength && ($start + 2 * $iLength) <= $pNums) && ($end    = $start + 2 * $iLength);
            ($rightLen <= $iLength && ($end - 2 * $iLength) >= 1) && ($start    = $end - 2 * $iLength);
        }

        if($page < $end) {
            if ($flag === true) {
				$str_page .= "<span class='page_num'><a href='?".$urlextend.$pname."=".$pNums."'>&gt;&gt;</a></span>";
            }
			$str_page .= '<span class="page_num"><a href="'.$url.'?'.$urlextend.$pname.'='.($page+1).'">&gt;</a></span>';
        }
		else
		{
			if ($flag === true) {
				$str_page .= "<span class='page_nolink'>&gt;&gt;</span>";
            }
			$str_page .= '<span class="page_nolink">&gt;</span>';
		}

		for($i = $end; $i >= $start; $i --) {
			$sUrl = '<span class="page_num"><a href="'.$url.'?'.$urlextend.$pname.'='.($i).'">'.$i.'</a></span>';
			$str_page .= ($i == $page) ? "<span class='page_num_nonce'>".$i."</span>" : $sUrl;
        }
		
		if($page > 1) {
			
			$str_page .= '<span class="page_num"><a href="'.$url.'?'.$urlextend.$pname.'='.($page-1).'">&lt;</a></span>';

        	if ($flag === true) {
				$str_page .= "<span class='page_num'><a href='?{$urlextend}&{$pname}=1'>&lt;&lt;</a></span>";
        	}
            
        }
		else
		{
			$str_page .= '<span class="page_nolink">&lt;</span>';

        	if ($flag === true) {
				$str_page .= "<span class='page_nolink'>&lt;&lt;</span>";
        	}
		}

        return $str_page;
    }
	
	/**
	 *
	 * 显示提示信息(基于jquery)
	 *
	 *
	 * 参数：string $message 提示信息
	 * masonsu 2010-3-17
	*/
	public static function tip($message)
	{
		if(strlen($message) > 0)
		{
			return '<script type="text/javascript">$(document).ready( function() { alertMsg(); } );function alertMsg() {$("#alert_div").fadeIn(1000);setTimeout("disAlert()", 2000);}function disAlert(){$("#alert_div").fadeOut(1000);}</script><div class="topsBox margin25" id="alert_div" style="display:none;"><h2><span class="org">提示：&nbsp;'.$message.'</span></h2></div>';
		}
		else
		{
			return '';
		}
	}

	/**
	 *
	 * 爱家团提示信息(基于jquery)
	 *
	 *
	 * 参数：string $message 提示信息
	 * masonsu 2010-3-17
	*/
	public static function tuan_tip($message)
	{
		if(strlen($message) > 0)
		{
			return '<script type="text/javascript">$(document).ready( function() { alertMsg(); } );function alertMsg() {$("#alert_div").fadeIn(1000);setTimeout("disAlert()", 2000);}function disAlert(){ $("#alert_div").fadeOut(1000);}</script><div id="alert_div" style="display:none;font-size:20px;font-family:\'黑体\';background:#FFCC00;padding:20px 0px;">提示:&nbsp;'.$message.'</div>';
		}
		else
		{
			return '';
		}
	}
	
	/**
	 *
	 * 显示提示信息(基于mootools)
	 *
	 *
	 * 参数：string $message 提示信息
	 * masonsu 2010-4-14
	*/
	public static function tip_mootools($message)
	{
		if(strlen($message) > 0)
		{
			return '<script type="text/javascript">var sum = 8;window.addEvent("domready", function() {$("alert_div").fadeIn = function (){if(sum >= 0){$("alert_div").setStyle("opacity",1-sum*(1/10));sum = sum - 1;setTimeout(\'$("alert_div").fadeIn()\',100);}else{sum = 8;setTimeout(\'$("alert_div").fadeOut()\',2000);}};$("alert_div").fadeOut = function (){if(sum >= 0){$("alert_div").setStyle("opacity",sum*(1/10));sum = sum - 1;setTimeout(\'$("alert_div").fadeOut()\',100);}else{$("alert_div").setStyle("display","none");}}; $("alert_div").setStyle("opacity","0");$("alert_div").setStyle("display","block");$("alert_div").fadeIn(sum);});</script><div class="topsBox margin25" id="alert_div" style="display:none;"><h2><span class="org">提示：&nbsp;'.$message.'</span></h2></div>';
		}
		else
		{
			return '';
		}
	}

	/*
	 *上传图片并获取返回信息
	 *
	 * 参数：
	 * 
	 * masonsu 2010-3-24
	*/
	public static function upload($p_login_name,$city,$product,$pic_url,$describe)
	{
		$p_login_name = urlencode($p_login_name);
		$city = urlencode($city);
		$product = urlencode($product);
		$pic_url = urlencode($pic_url);
		$describe = urlencode($describe);
		$link = 'http://v2.imgup.focus.cn/upload_img_ihome.php?p_login_name='.$p_login_name.'&city='.$city.'&product='.$product.'&pic_url='.$pic_url.'&describe='.$describe;

		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $link);
		curl_setopt($ch, CURLOPT_HEADER, 0);
		ob_start();
		if (!curl_exec($ch)) { return false; }
		$msg = ob_get_contents();
		ob_end_clean();
		curl_close($ch);

		return $msg;

	}

	
	/*
	 * 获取用户定制服务
	 *
	 * 参数：$id,用户id; $type,服务类型
	 * masonsu 2010-3-24
	*/
	public static function service_order($id,$type)
	{
		$service = new ServiceAction();

		//查询问题和答案
		$arr_data = $service->getQuestionAnswer($type);

		//查询用户已定制服务
		$arr_temp = $service->getServiceInfo($id,$type);

		$arr_check = array();
		foreach($arr_temp as $value)
		{
			$arr_check[$value['question_id']] = $value['answer_id'];
		}

		//查询服务shortname
		$arr_temp = $service->getServiceName($type);

		$arr_choice = array();
		foreach($arr_temp as $value)
		{
			$arr_choice[$value['question_id']]['shortname'] = $value['question_for_short'];
			$arr_choice[$value['question_id']]['answer'] = '无';
		}

		//组合数据
		//$content = array();
		foreach($arr_data as $item)
		{
			//$content[$item['question_id']]['question'] = $item['question_content'];
			//$content[$item['question_id']]['answer'][$item['answer_id']]['content'] = $item['answer_content'];
			//$content[$item['question_id']]['answer'][$item['answer_id']]['checked'] = ($arr_check[$item['question_id']] == $item['answer_id'])?'checked="checked"':'';
			if($arr_check[$item['question_id']] == $item['answer_id'])
			{
				$arr_choice[$item['question_id']]['answer'] = $item['answer_content'];
			}
		}
		return $arr_choice;
	}
	
	/*
	 * 截取字符串长度，支持多字节
	 *
	 * 参数：
	 * 
	 * masonsu 2010-3-24
	*/
	public static function substring($str,$size,$skiphtml=0) {
		$ret = '';
		if ($size<=0) {
			return;
		}
		$wrap=true;
		$html=false;
		if ($size<2) $size=2;
		$j=0;
		if ($skiphtml) {
			$str=trim(strip_tags($str));
		}
		$num=strlen($str);
		for($i=0;$i<$num;$i++) {
			if ($str[$i]=="<" && !$html) {
				$html=true;
				$ret.=$str[$i];
				continue;
			}
			if ($str[$i]==">" && $html) {
				$html=false;
				$ret.=$str[$i];
				continue;
			}
			if ($html) {
				$ret.=$str[$i];
				continue;
			}
			if ($str[$i]=="\r") {
				continue;
			}
			if (($str[$i]=="\n" || $str[$i]==" " || $str[$i]=="\t") && !$space) {
				$space=true;
				$ret.=$str[$i];
				$j++;
				continue;
			} else if ($str[$i]=="\n" || $str[$i]==" " || $str[$i]=="\t") {
				$ret.=$str[$i];
				continue;
			} else {
				$space=false;
			}
            //echo "$i  ".ord($str[$i])."  $str[$i]"."  <br>"; 
			if (ord($str[$i])>128) {
			    if($i<$num-1){
			      $j++;
			      $ret.=$str[$i];
			      $i++;
			      $j++;
    		      $ret.=$str[$i];
                }
			}else{
			   $j++;
			   $ret.=$str[$i];
			}
			if($j>=$size) break;
		}
		return $ret;
	}

	/**
	 * 获取图片url地址. 
	 *
	 * @param String $product_name  查询图片所在产品的名称(esf,ihome) 
	 * @param string $pic_url 数据库中保存的url或id
	 * @param int $width 图片宽度. 
	 * @param int $height 图片高度. 
	 * @return string 图片url地址 
	 */
	public static function getImgUrl($pic_url,$width=0,$height=0,$product_name='ihome')
	{
		$pic = basename($pic_url);
		if($arr_pic = explode('.',$pic))
			return FSImageUtility::getImgUrl($product_name,$arr_pic[0],$arr_pic[1],$width,$height);
		else
			return '';
	}

	/*
     * 翻页方法
     *
     * @param int $count                   总数
     * @param int $limit                   每页最多显示多少数据
	 * @param int $offset                  偏移量
     * @param int $page                    当前页码数
     * @param string $url                  处理程序名
     * @param bool $flag                   是否显示首尾页
     *
     * return string             返回的分页按钮(样式显示须引入相关ＣＳＳ文件)
	 *                                       http://ihome.sohu.com/css/style.css
     *
	 * masonsu 2010-4-9
     */
    public static function showPage_front($count, $limit, $offset,$page, $url,$flag=false) 
	{
		$url_name = $url;
		$url_ext = "";

		$pNums = ceil($count / $limit);         //计算总页数

		$str_page = '';

        $iLength    = 4;
        $page = intval($page);
        if ($page <= 0) {
        	$page = 1;
        }

		$page_start = $count?($offset+1):0;
		$page_end = (($offset+$limit)>$count)?$count:($offset+$limit);

		$str_page .= "<div class='left'>共 <em class='org'>".$count."</em> 条记录 这是 <em class='org'>".$page_start."-".$page_end."</em> 条</div>";

        $start  = $page - $iLength;
        ($start < 1) && $start = 1;
        $end    = $start + 2 * $iLength;
        ($end > $pNums) && $end = $pNums;

        $leftLen    = $page - $start;
        $rightLen   = $end - $page;

        if($end - $start < 2 * $iLength) {    //补齐长度
            ($leftLen <= $iLength && ($start + 2 * $iLength) <= $pNums) && ($end    = $start + 2 * $iLength);
            ($rightLen <= $iLength && ($end - 2 * $iLength) >= 1) && ($start    = $end - 2 * $iLength);
        }

        if($page < $end) {
            if ($flag === true) {
				$str_page .= "<span class='page_num'><a href='".$url_name.'/'.$pNums.$url_ext."'>&gt;&gt;</a></span>";
            }
			$str_page .= '<span class="page_num"><a href="'.$url_name.'/'.($page+1).$url_ext.'">&gt;</a></span>';
        }
		else
		{
			if ($flag === true) {
				$str_page .= "<span class='page_nolink'>&gt;&gt;</span>";
            }
			$str_page .= '<span class="page_nolink">&gt;</span>';
		}

		for($i = $end; $i >= $start; $i --) {
			$sUrl = '<span class="page_num"><a href="'.$url_name.'/'.$i.$url_ext.'">'.$i.'</a></span>';
			$str_page .= ($i == $page) ? "<span class='page_num_nonce'>".$i."</span>" : $sUrl;
        }
		
		if($page > 1) {
			
			$str_page .= '<span class="page_num"><a href="'.$url_name.'/'.($page-1).$url_ext.'">&lt;</a></span>';

        	if ($flag === true) {
				$str_page .= "<span class='page_num'><a href='".$url_name.'/1'.$url_ext."'>&lt;&lt;</a></span>";
        	}
            
        }
		else
		{
			$str_page .= '<span class="page_nolink">&lt;</span>';

        	if ($flag === true) {
				$str_page .= "<span class='page_nolink'>&lt;&lt;</span>";
        	}
		}

        return $str_page;
	}

	/*
	 * @abstract: 返回唯一的一个整数值 (一个小时以内)
	 * @return: unique integer
	 * @author: xiaoliangyang
	 * @date: 2010-08-17
	 */
	public static function getUniqueInteger () {
	
		list($usec, $sec) = explode(' ' , microtime());
		$sec  = $sec - strtotime(date("Y-m-d H:00:00"));
	
		$unique_int = $sec * 100000 + (int)($usec * 100000);
		return $unique_int;
	}

	/*
	 * 根据电子邮件，生成最多7个字符的名称，作为nickname返回
	 * @param: email string
	 * @return: nickname string (strlen(nickname) <= 7)
	 * @author: xiaoliangyang
	 */
	public static function build_nickname($email)
	{
		$email = strtolower(trim(strval($email)));
		list($name, $extra) = explode('@', $email);
		if (empty($name))
			return substr($email, 0, 15);

		return self::substring($name, 15);
	}

	/*
	 * 展示消息模板
	 */
	public static function errormsg ($msg, $msg_title = NULL) {

		$msg_title = empty($msg_title) ? '有错误发生' : trim($msg_title);
		$msg       = trim($msg);

		FSTemplate::assign('page_title', $msg_title);
		FSTemplate::assign('msg_title',  $msg_title);
		FSTemplate::assign('msg', $msg);
		FSTemplate::Display("apply/tuan_msg.tpl");
		exit(0);
	}
	
	public static function i18nErrorMsg ($errormsg) {
		$error = trim(strval($errormsg));
		switch($error)
		{
			case 'INVALID_ORDER':
				$errormsg = '<font color=red>订单无效或者不存在</font>';		
				break;
			case 'INVALID_ACTIVITY':
				$errormsg = '<font color=red>活动无效或者不存在</font>';
				break;
			case 'TIMEOUT':
				$errormsg = '<font color=red>活动已经结束</font>';
				break;
			case 'INVALID_PRODUCT':
				$errormsg = '<font color=red>产品无效或者不存在</font>';
				break;
			case 'TOTAL_QUANTITY':
				$errormsg = '<font color=red>产品卖光了</font>';
				break;
			case 'MAX_BUY_LIMIT':
				$errormsg = '<font color=red>个人超过了购买限制</font>';
				break;
			case 'MAX_TOTAL_QUANTITY':
				$errormsg = '<font color=red>产品库存不够，购买失败。</font>';
				break;
			case 'ORDER_HAS_BEEN_PAID':
				$errormsg = '<font color=red>此产品已支付!</font>';
				break;
			case 'NOT_ENOUGH_MONEY':
				$errormsg = '<font color=red>帐户金额不足以支付订单!</font>';
				break;
			default:
				$errormsg = '请根据您的情况';
				break;
		}
		return $errormsg;
	}

	public static function loadGlobalTemplateVars () 
	{
		$only_verified = FALSE;
		$template = new TemplateAction();
		$template->setCommonCityChannels();
		$template->setCommonActivityMenus();
	}

	/*
	 * 邮件地址是否属于搜狐域名
	 *
	 * @param	string	email
	 * @return	boolean
	 */
	public static function isSohuDomainEmail($email)
	{
		if (preg_match('/^.+@(?:sohu\.com|sogou\.com|chinaren\.com|focus\.cn|vip\.sohu\.com|game\.sohu\.com|17173\.com)$/i', $email, $m)) 
			return TRUE;
		else
			return FALSE;
	}

	/*
	 * 构建能自动登录到搜狐Passport，并跳转回爱家团的登录URL地址
	 *
	 * @param	string	email
	 * @param	string	plain password
	 * @return	string	url for sohu passport login
	 */
	public static function buildSohuAutoLoginUrl ($email, $passwd, $return_url)
	{
		$passport = $email;
		$password = $passwd;
		$md5passwd= md5($passwd);
		$appid    = 1028;
		$return_url = trim(strval($return_url));
	
		$sohuPassportApi = new ComSohuPassportApi();
		$sohuPassportApi->setPassport($passport);
		$response = $sohuPassportApi->login($password);
	
		if (isset($response['status']) AND $response['status'] == 0)
		{
			$return_url = 'http://'. site::domain() . '/passport/login_callback?referer=' . $return_url;
			$return_url = "http://passport.sohu.com/sso/login_js.jsp?userid={$passport}&password={$md5passwd}&persistentcookie=1&pwdtype=1&appid={$appid}&ru={$return_url}";
		}
		else
			$return_url = '';

		return $return_url;
	}

	/*
	 * 根据邮件账户，返回邮箱的互联网登录地址
	 *	
	 * @param	string	email 
	 * @return	string	url
	 */
	public static function getWebmailAddressFromEmail($email)
	{
		$webmail_address = '#';
		$ms = explode('@', $email);
		if (count($ms) > 1) {
			$mail_domain = $ms[1];	
			if ($mail_domain == 'gmail.com')
				$webmail_address = 'http://mail.google.com';
			else if (in_array($mail_domain, array('51.com','hotmail.com', 'msn.com', 'msn.cn')))
				$webmail_address = 'http://www.' . $mail_domain;	
			else
				$webmail_address = 'http://mail.' . $mail_domain;
		}

		return $webmail_address;
	}

	/*
	 * 返回info.config.inc.php里面的CITY CODE
	 *
	 * @param	string		city name
	 * @return	string		city code
	 */
	public static function getCityCodeByName($city_name)
	{
		global $CITY_CONFIG;
		$city_name = trim(strval($city_name));
		$province_citys = array('北京', '天津', '上海', '重庆');
		if (in_array($city_name, $province_citys))
		{
			foreach ($CITY_CONFIG as $pcode => & $areas) 
			{
				if ($areas['name'] == $city_name)
				{
					$codes = array_keys($areas['city']);
					$code  = $codes[0];
					break;
				}
					
			}
		}
		else
		{
			foreach ($CITY_CONFIG as $pcode => & $cities) {
				foreach ($cities['city']  as $city_code => $city) {
					if ($city == $city_name) {
						$code = $city_code;
						break;
					}
				}
			}

		} // end if

		if (empty($code))
			$code = '110101';

		return $code;
	}

 	function gbk_wordwrap($str, $width, $break = "\n")
	{
	    $return = '';
	    $br_width = mb_strlen($break, 'GBK');
	    for($i = 0, $count = 0; $i < mb_strlen($str, 'GBK'); $i++, $count++)
	    {
	        if (mb_substr($str, $i, $br_width, 'GBK') == $break)
	        {
	            $count = 0;
	            $return .= mb_substr($str, $i, $br_width, 'GBK');
	            $i += $br_width - 1;
	        }
	       
	        if ($count >= $width)
	        {
	            $return .= $break;
	            $count = 0;
	        }
	       
	        $return .= mb_substr($str, $i, 1, 'GBK');
	    }
	   
	    return $return;
	}
	
	/** UTF-8转换为GB2312,无法转换的转为Unicode编码形式(如:&#8226;),与PDO转码规则相统一。
	 *
	 * masonsu 2010-4-22
	 */
	public static function utf8_to_gb2312($name)
	{
		$tostr = "";
		for($i=0;$i<strlen($name);$i++)
		{
			$curbin = ord(substr($name,$i,1));
			if($curbin < 0x80)
			{
				$tostr .= substr($name,$i,1);
			}
			elseif($curbin < bindec("11000000"))
			{
				$str = substr($name,$i,1);
				$tostr .= "&#".ord($str).";";
			}
			elseif($curbin < bindec("11100000"))
			{
				$str = substr($name,$i,2);
				$tostr .= "&#".self::get_unicode_char($str).";";
				$i += 1;
			}
			elseif($curbin < bindec("11110000"))
			{
				$str = substr($name,$i,3);
				$gstr= iconv("UTF-8","GB2312",$str);
				if(!$gstr)
				{
					$tostr .= "&#".self::get_unicode_char($str).";";
				}
				else
				{
					$tostr .= $gstr;
				}
				$i += 2;
			}
			elseif($curbin < bindec("11111000"))
			{
				$str = substr($name,$i,4);
				$tostr .= "&#".self::get_unicode_char($str).";";
				$i += 3;
			}
			elseif($curbin < bindec("11111100"))
			{
				$str = substr($name,$i,5);
				$tostr .= "&#".self::get_unicode_char($str).";";
				$i += 4;
			}
			else
			{
				$str = substr($name,$i,6);
				$tostr .= "&#".self::get_unicode_char($str).";";
				$i += 5;
			}
		}
		return $tostr;
	}
	
	/** ASCII码到Unicode码的转换规则
	 *
	 * masonsu 2010-4-22
	 */
	public static function get_unicode_char($str)
	{
		$temp = "";
		for($i=0;$i<strlen($str);$i++)
		{
			$x = decbin(ord(substr($str,$i,1)));
			if($i == 0)
			{
				$s = strlen($str)+1;
				$temp .= substr($x,$s,8-$s);
			}
			else
			{
				$temp .= substr($x,2,6);
			}
		}
		return bindec($temp);
	}

	public static function createAuthString ($string, $token_key_type = NULL)
	{
		global $GLOBAL_TOKEN_KEYS;

		$tokens = $GLOBAL_TOKEN_KEYS;
		if (is_array($tokens) 
				AND !empty($token_key_type) 
				AND isset($tokens[$token_key_type]))
			$token_key = $tokens[$token_key_type];
		else
			$token_key = 'lPa2K*1,%123';

		return md5("{$string}{$tokey_key}");
	}

	public static function checkAuthString ($string, $auth_string, $token_key_type = NULL)
	{
		if (empty($auth_string))
			return FALSE;	

		$auth_str = self::createAuthString ($string, $token_key_type);
		if ($auth_str == $auth_string)
			return TRUE;
		else
			return FALSE;
	}



	/*
     * 翻页方法2
     *
     * @param int $count                   总数
     * @param int $limit                   每页最多显示多少数据
	 * @param int $offset                  偏移量
     * @param int $page                    当前页码数
     * @param string $url                  处理程序名
     * @param bool $flag                   是否显示首尾页
     *
     * return string             返回的分页按钮(样式显示须引入相关ＣＳＳ文件)
	 *                                       http://ihome.sohu.com/css/style.css
     *
	 *  2010-4-9
     */
    public static function showPage_front2($count, $limit, $offset,$page, $url, $url_ext="", $flag=false) 
	{
		$url_name = $url;

		$pNums = ceil($count / $limit);         //计算总页数

		$str_page = '';

        $iLength    = 4;
        $page = intval($page);
        if ($page <= 0) {
        	$page = 1;
        }

		$page_start = $count?($offset+1):0;
		$page_end = (($offset+$limit)>$count)?$count:($offset+$limit);

		$str_page .= "<div style='float:left;'>共 <em class='org'>".$count."</em> 条</div>";

        $start  = $page - $iLength;
        ($start < 1) && $start = 1;
        $end    = $start + 2 * $iLength;
        ($end > $pNums) && $end = $pNums;

        $leftLen    = $page - $start;
        $rightLen   = $end - $page;

        if($end - $start < 2 * $iLength) {    //补齐长度
            ($leftLen <= $iLength && ($start + 2 * $iLength) <= $pNums) && ($end    = $start + 2 * $iLength);
            ($rightLen <= $iLength && ($end - 2 * $iLength) >= 1) && ($start    = $end - 2 * $iLength);
        }
		
		if($page > 1) {
        	if ($flag === true) {
				$str_page .= "<a href='".$url_name.'/1'.$url_ext."'>首页</a>";
        	}
			$str_page .= '<a href="'.$url_name.'/'.($page-1).$url_ext.'">上页</a>';
        }
		else
		{
        	if ($flag === true) {
				$str_page .= "首页 ";
        	}
			$str_page .= '上页';
		}

		for($i = $start; $i <= $end; $i ++) {
			$sUrl = '<a href="'.$url_name.'/'.$i.$url_ext.'">'.$i.'</a>';
			$str_page .= ($i == $page) ? "<span>".$i."</span>" : $sUrl;
        }

        if($page < $end) {
			$str_page .= '<a href="'.$url_name.'/'.($page+1).$url_ext.'">下页</a>';
            if ($flag === true) {
				$str_page .= "<a href='".$url_name.'/'.$pNums.$url_ext."'>尾页</a>";
            }
        }
		else
		{
			$str_page .= '下页 ';
			if ($flag === true) {
				$str_page .= "尾页";
            }
		}


        return $str_page;
	}


	// 逗号分隔的字符串转换成数组
	public static function dottedString2Array ($string) 
	{
		$string = trim(strval($string));
		$ls     = split(',', $string);
		$as     = array();
		foreach ($ls as $i)
			if (!empty($i))
				$as[] = $i;

		return $as;
	}


	public static function filterCssStyle ($html_content)
	{

		//$html_content = preg_replace('/<link[^>]+>/i', '', $html_content);
		return $html_content;
	}

	/*
	 * XSS 注入防范
	 */
	public static function xssFilter ($string, $type = FILTER_SANITIZE_STRING)
	{
		if (! empty($type))
		{
			$type = trim(strval($type));
			return filter_var($string, $type);
		}
		else
			return $string;
	}


	/**
	 * Tests if an array is associative or not.
	 *
	 *     // Returns TRUE
	 *     Arr::is_assoc(array('username' => 'john.doe'));
	 *
	 *     // Returns FALSE
	 *     Arr::is_assoc('foo', 'bar');
	 *
	 * @param   array   array to check
	 * @return  boolean
	 */
	public static function is_assoc(array $array)
	{
		// Keys of the array
		$keys = array_keys($array);

		// If the array keys of the keys match the keys, then the array must
		// not be associative (e.g. the keys array looked like {0:0, 1:1...}).
		return array_keys($keys) !== $keys;
	}

	/**
	 * Merges one or more arrays recursively and preserves all keys.
	 * Note that this does not work the same as [array_merge_recursive](http://php.net/array_merge_recursive)!
	 *
	 *     $john = array('name' => 'john', 'children' => array('fred', 'paul', 'sally', 'jane'));
	 *     $mary = array('name' => 'mary', 'children' => array('jane'));
	 *
	 *     // John and Mary are married, merge them together
	 *     $john = Arr::merge($john, $mary);
	 *
	 *     // The output of $john will now be:
	 *     array('name' => 'mary', 'children' => array('fred', 'paul', 'sally', 'jane'))
	 *
	 * @param   array  initial array
	 * @param   array  array to merge
	 * @param   array  ...
	 * @return  array
	 */
	public static function merge(array $a1, array $a2)
	{
		$result = array();
		for ($i = 0, $total = func_num_args(); $i < $total; $i++)
		{
			// Get the next array
			$arr = func_get_arg($i);

			// Is the array associative?
			$assoc = Util::is_assoc($arr);

			foreach ($arr as $key => $val)
			{
				if (isset($result[$key]))
				{
					if (is_array($val))
					{
						if (Util::is_assoc($val))
						{
							// Associative arrays are merged recursively
							$result[$key] = Util::merge($result[$key], $val);
						}
						else
						{
							// Find the values that are not already present
							$diff = array_diff($val, $result[$key]);

							// Indexed arrays are merged to prevent duplicates
							$result[$key] = array_merge($result[$key], $diff);
						}
					}
					else
					{
						if ($assoc)
						{
							// Associative values are replaced
							$result[$key] = $val;
						}
						elseif ( ! in_array($val, $result, TRUE))
						{
							// Indexed values are added only if they do not yet exist
							$result[] = $val;
						}
					}
				}
				else
				{
					// New values are added
					$result[$key] = $val;
				}
			}
		}

		return $result;
	}

	/**
	 * url附加参数.
	 * @param params=array('key'=>'val');
	 */
	public static function addUrlParams($url,$params=array()) {
		if( !is_array($params) || !count($params) ) {
			return $url;
		}
		
		if( !strpos($url,"?") ) {
			$url .= "?";
		} else {
			$url .= "&";
		}
		foreach($params as $key=>$val) {
			$url .= "$key=$val&";	
		}

		$url = substr($url,0,-1);
		
		return $url;
	}
	
	
	/**
	 * 产品产品单价过万处理方法.
	 * @param params=array('key'=>'val');
	 */
	public static function changeUnit(& $save, & $unit_price, & $original_price ) 
	{

		if(preg_match('/^.*<span>[^>]+>￥(\d+)<\/span>.*$/', $save, $m) || preg_match('/￥(\d+)/', $save, $m))
				$save = $m[1];
		
		if(preg_match('/^.*<span>[^>]+>￥(\d+)<\/span>.*$/', $unit_price, $m) || preg_match('/￥(\d+)/', $unit_price, $m))
				$unit_price = $m[1];

		if(preg_match('/^.*<span>[^>]+>￥(\d+)<\/span>.*$/', $original_price, $m) || preg_match('/￥(\d+)/', $original_price, $m))
				$original_price = $m[1];				

		if (! is_null($save) && intval($save) > 0)
		{
			if ($save >= 10000)
			{
					$save = ($save % 10000 == 0 ? '￥'.intval($save / 10000): '￥'.sprintf("%.01f", $save/10000)) . '万';
			}
			else
				$save = '￥'.($save);
		}

		if (! is_null($unit_price) && intval($unit_price) > 0)
		{
			if ($unit_price >= 10000)
				$unit_price = ($unit_price % 10000 == 0 ? intval($unit_price / 10000): sprintf("%.01f", $unit_price/10000)) . '万';
		}

		if (! is_null($original_price) && intval($original_price) > 0)
		{
			if ($original_price >= 10000)
				$original_price = ($original_price % 10000 == 0 ? '￥'.intval($original_price / 10000): '￥'.sprintf("%.01f", $original_price/10000)) . '万';
			else
				$original_price = '￥'.($original_price);
		}

		return;
	}
	
}
